package com.vickw.websocketdemo.controller;

import com.alibaba.fastjson.JSONObject;
import com.vickw.websocketdemo.config.RsaConfig;
import com.vickw.websocketdemo.util.RsaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * @version 1.0
 * @Description：
 * @Author VickW
 * @Date 2025/3/3 21:28
 */
@RestController("/rsa")
public class RsaController {

    @Autowired
    private RsaConfig rsaConfig;

    @GetMapping("/test")
    public String testRsa(String request) {
        boolean verify = false;
        boolean verify1 = false;
        try {
            JSONObject signatureHead = assembleSignatureHead();

            JSONObject requestBody1 = new JSONObject();
            requestBody1.put("sessionId", request);

            String sign = assembleRequest(requestBody1, signatureHead);

            JSONObject signatureHead1 = assembleSignatureHead();

            JSONObject requestBody = new JSONObject();
            requestBody.put("sessionId", "1234561");
            verify = RsaUtils.verify(signatureHead, requestBody, RsaUtils.loadPublicKey(rsaConfig.getPublicKey()), sign);
            verify1 = RsaUtils.verify(signatureHead1, requestBody, RsaUtils.loadPublicKey(rsaConfig.getPublicKey()), sign);

            return String.format("验签结果1: %s, 验签结果2: %s", verify, verify1);
        } catch (Exception e) {
            return String.format("验签结果1: %s, 验签结果2: %s", verify, verify1);

        }

    }

    /**
     * "signatureHead": {
     * "app": "chatbot",
     * "reqTime": "1720153874529",
     * "reqMsgId": "req-4a592e7b-cc86-4d9f-a89d-82f6c7a1e450"
     * }
     *
     * @return
     */
    private JSONObject assembleSignatureHead() {

        JSONObject signatureHeadBody = new JSONObject();
        signatureHeadBody.put("app", "chatbot");
        signatureHeadBody.put("reqTime", System.currentTimeMillis());
        signatureHeadBody.put("reqMsgId", UUID.randomUUID());

        return signatureHeadBody;

    }

    /**
     * assembleRequest
     *
     * @param request
     */
    private String assembleRequest(JSONObject request, JSONObject signatureHead) throws Exception {

        JSONObject requestBody = new JSONObject();

        // signatureHead
        //JSONObject signatureHead = assembleSignatureHead();

        // request
        requestBody.put("request", request);
        requestBody.put("signatureHead", signatureHead);
        String sign = RsaUtils.sign(signatureHead, request, RsaUtils.loadPrivateKey(rsaConfig.getPrivateKey()));
        //requestBody.put("signature", sign);

        return sign;
    }

}
